import React, { useEffect, useState } from "react";
import { 
  Card, 
  Row, 
  Col, 
  Descriptions, 
  Avatar, 
  Tag, 
  Progress, 
  Divider,
  Button,
  message,
  Modal,
  Form,
  Input,
  Space,
  InputNumber,
  Spin,
  Upload,
  Table,
    Tooltip,
} from "antd";
import { 
  UserOutlined,
  MailOutlined,
  EnvironmentOutlined,
  IdcardOutlined,
  CalendarOutlined,
  CloudUploadOutlined,
  CloudDownloadOutlined,
  StarOutlined,
  LinkOutlined,
  SafetyCertificateOutlined,
  EditOutlined,
  LockOutlined,
  PlusOutlined,
  InfoCircleOutlined,
  DeleteOutlined

} from '@ant-design/icons';
import { LoadingOutlined, CameraOutlined, } from '@ant-design/icons';
import { useDispatch } from "react-redux";
import { fetchUserInfo ,modifypassword,fetchresetVerification,addInviteCodeUses,uploadAvatar,deleteInviteCode,modifyUserInfo,createInviteCode,exchangePoints,fetchInviteCodes} from "../../store/modules/userStore";
import './profile.css';
import { RouterAuth } from "../../router/routerAuth";

const Profile = () => {
  const dispatch = useDispatch();
  const [userInfo, setUserInfo] = useState({});
  const [loading, setLoading] = useState(true);
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [passwordModalVisible, setPasswordModalVisible] = useState(false);
  const [editForm] = Form.useForm();
  const [passwordForm] = Form.useForm();
  const [countdown, setCountdown] = useState(0);
  const [sendingCode, setSendingCode] = useState(false);
  const [avatarLoading, setAvatarLoading] = useState(false);
  const [inviteModalVisible, setInviteModalVisible] = useState(false);
  const [exchangeModalVisible, setExchangeModalVisible] = useState(false);
  const [inviteForm] = Form.useForm();
  const [exchangeForm] = Form.useForm();
  const [loadingInvite, setLoadingInvite] = useState(false);
  const [loadingExchange, setLoadingExchange] = useState(false);
  const [inviteCodes, setInviteCodes] = useState([]);
  const [inviteCodesLoading, setInviteCodesLoading] = useState(false);
  const [showInviteCodes, setShowInviteCodes] = useState(false);
  

  useEffect(() => {
    loadUserInfo();
  }, [dispatch]);

  // 倒计时效果
  useEffect(() => {
    if (countdown > 0) {
      const timer = setTimeout(() => setCountdown(countdown - 1), 1000);
      return () => clearTimeout(timer);
    }
  }, [countdown]);


  // 获取邀请码函数
  const loadInviteCodes = async () => {
    try {
      setInviteCodesLoading(true);
      const res = await dispatch(fetchInviteCodes());
      
      if (res.code === 0) {
        setInviteCodes(res.data || []);
        setShowInviteCodes(true);
      } else {
         setInviteCodes(res.data || []);
        setShowInviteCodes(true);
      }
    } catch (error) {
      console.error('获取邀请码出错:', error);
      message.error('获取邀请码出错');
    } finally {
      setInviteCodesLoading(false);
    }
  };

  // 更新inviteColumns定义
const inviteColumns = [
  {
    title: '邀请码',
    dataIndex: 'code',
    key: 'code',
    render: (text) => <Tag color="blue">{text}</Tag>,
  },
  {
    title: '最大使用次数',
    dataIndex: 'maxUses',
    key: 'maxUses',
  },
  {
    title: '剩余使用次数',
    dataIndex: 'remainingUses',
    key: 'remainingUses',
    render: (text, record) => (
      <Tooltip title="点击增加使用次数">
        <span 
          style={{ 
            color: text > 0 ? 'green' : 'red',
            cursor: 'pointer',
            textDecoration: 'underline'
          }}
          onClick={() => handleAddInviteCodeUses(record.code)}
        >
          {text}
        </span>
      </Tooltip>
    ),
  },
  {
    title: '过期时间',
    dataIndex: 'expiryTime',
    key: 'expiryTime',
  },
  {
    title: '操作',
    key: 'action',
    render: (_, record) => (
      <Space>
        <Button 
          type="link" 
          onClick={() => {
            navigator.clipboard.writeText(record.code);
            message.success('邀请码已复制');
          }}
        >
          复制
        </Button>
        <Button 
          type="link" 
          onClick={() => handleAddInviteCodeUses(record.code)}
          icon={<PlusOutlined />}
        >
          增加次数
        </Button>
        <Button 
          type="link" 
          danger
          onClick={() => handleDeleteInviteCode(record.code)}
          icon={<DeleteOutlined />}
        >
          删除
        </Button>
      </Space>
    ),
  },
];

  const handleCreateInvite = async () => {
  try {
    setLoadingInvite(true);
    const values = await inviteForm.validateFields();
    const res = await dispatch(createInviteCode(values.code));
    
    if (res.code === 0) {
      message.success('邀请码生成成功');
      // 关闭模态框并重置表单
      setInviteModalVisible(false);
      inviteForm.resetFields();
      
      // 重点：生成成功后刷新邀请码列表
      await loadInviteCodes();
      
      // 可选：显示生成的邀请码信息
      Modal.info({
        title: '邀请码信息',
        content: (
          <div>
            <p>邀请码: {res.data.code}</p>
            <p>最大使用次数: {res.data.maxUses}</p>
            <p>剩余使用次数: {res.data.remainingUses}</p>
            <p>过期时间: {res.data.expiryTime}</p>
          </div>
        ),
      });
    } else {
      message.error(res.msg || '生成邀请码失败');
    }
  } catch (error) {
    console.error('生成邀请码出错:', error);
    message.error('生成邀请码出错');
  } finally {
    setLoadingInvite(false);
  }
};

  // 兑换上传量处理函数
  const handleExchangePoints = async () => {
    try {
      setLoadingExchange(true);
      const values = await exchangeForm.validateFields();
      const res = await dispatch(exchangePoints(values.points));
      
      if (res.message) {
        message.success(res.message);
        setExchangeModalVisible(false);
        exchangeForm.resetFields();
        loadUserInfo(); // 刷新用户信息
      } else if (res.error) {
        message.error(res.error);
      }
    } catch (error) {
      console.error('兑换上传量出错:', error);
      message.error('兑换上传量出错');
    } finally {
      setLoadingExchange(false);
    }
  };
  const loadUserInfo = () => {
    setLoading(true);
    dispatch(fetchUserInfo())
      .then(res => {
        if (res && res.code === 0) {
          setUserInfo(res.data);
          editForm.setFieldsValue({
            username: res.data.username,
            address: res.data.address
          });
        } else {
          message.error(res?.msg || '获取用户信息失败');
        }
      })
      .catch(err => {
        console.error("获取用户信息错误：", err);
        message.error('获取用户信息出错');
      })
      .finally(() => {
        setLoading(false);
      });
  };

  const formatBytes = (bytes, decimals = 2) => {
  if (bytes === 0) return '0 Bytes';
  const k = 1024;
  const dm = decimals < 0 ? 0 : decimals;
  const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  
  // 确保至少显示2位数字（如1.00而不是1）
  const value = (bytes / Math.pow(k, i)).toFixed(dm);
  
  // 移除不必要的.00后缀
  const formattedValue = value.replace(/\.?0+$/, '');
  
  return `${formattedValue} ${sizes[i]}`;
};

  // 计算分享率颜色
  const getRatioColor = (ratio) => {
    if (ratio >= 1) return '#52c41a'; // 绿色
    if (ratio >= 0.5) return '#faad14'; // 橙色
    return '#f5222d'; // 红色
  };

  // 打开编辑模态框
  const showEditModal = () => {
    setEditModalVisible(true);
  };

  // 提交编辑表单
  const handleEditSubmit = () => {
    editForm.validateFields()
      .then(values => {
        dispatch(modifyUserInfo(values))
        .then(data => {
          if (data.code === 0) {
            message.success('修改成功');
            setEditModalVisible(false);
            loadUserInfo();
          } else {
            message.error(data.msg || '修改失败');
          }
        })
        .catch(error => {
          console.error('修改出错:', error);
          message.error('修改出错');
        });
      })
      .catch(info => {
        console.log('验证失败:', info);
      });
  };
 // 修改handleAddInviteCodeUses函数
const handleAddInviteCodeUses = async (code) => {
  try {
    const res = await dispatch(addInviteCodeUses(code));
    if (res.code === 0) {
      message.success('邀请码使用次数已增加');
      loadInviteCodes();
      loadUserInfo();
    } else if (res.msg === '可用积分不足') {
      Modal.error({
        title: '积分不足',
        content: '您的积分不足，无法增加邀请码使用次数。',
        okText: '知道了'
      });
    } else {
      message.error(res.msg || '操作失败');
    }
  } catch (error) {
    console.error('增加邀请码次数出错:', error);
    message.error('操作出错');
  }
};
// 在Profile组件中添加删除处理函数
const handleDeleteInviteCode = async (code) => {
  Modal.confirm({
    title: '确认删除邀请码',
    content: `确定要删除邀请码 ${code} 吗？此操作不可撤销。`,
    okText: '确认删除',
    okType: 'danger',
    cancelText: '取消',
    onOk: async () => {
      try {
        const res = await dispatch(deleteInviteCode(code));
        if (res.code === 0) {
          message.success(res.data || '删除成功');
          loadInviteCodes(); // 刷新邀请码列表
        } else {
          message.error(res.msg || '删除失败');
        }
      } catch (error) {
        console.error('删除邀请码出错:', error);
        message.error('删除邀请码出错');
      }
    }
  });
};
  // 发送验证码
  const sendVerificationCode = () => {
    setSendingCode(true);
    dispatch(fetchresetVerification()).then(data => {
      if (data.code === 0) {
        message.success('验证码已发送');
        setCountdown(10); // 
      } else {
        message.error(data.msg || '发送验证码失败');
      }
    })
    .catch(error => {
      console.error('发送验证码出错:', error);
      message.error('发送验证码出错');
    })
    .finally(() => {
      setSendingCode(false);
    });
  };

  // 提交修改密码表单
  const handlePasswordSubmit = () => {
    passwordForm.validateFields()
      .then(values => {
       dispatch(modifypassword(values))
        .then(data => {
          if (data.code === 0) {
            message.success('密码修改成功');
            setPasswordModalVisible(false);
            passwordForm.resetFields();
          } else {
            message.error(data.msg || '密码修改失败');
          }
        })
        .catch(error => {
          console.error('修改密码出错:', error);
          message.error('修改密码出错');
        });
      })
      .catch(info => {
        console.log('验证失败:', info);
      });
  };

  // 新增头像上传方法
const handleAvatarUpload = (info) => {
  const  {file}  = info;
  setAvatarLoading(true);
  const formData = new FormData();
  formData.append("file", file);
  console.log(formData.has("file"))
  dispatch(uploadAvatar(formData))
  .then(data => {
    
    if (data.code === 0) {
      message.success('头像上传成功');
      setUserInfo(prev => ({...prev, avatar: data.data}));
    } else {
      message.error(data.msg || '头像上传失败');
    }
  })
  .catch(error => {
    console.error('上传出错:', error);
    message.error('上传出错');
  })
  .finally(() => {
    setAvatarLoading(false);
  });
};

  return (
    <RouterAuth>
    <div className="profile-container">
      <Card 
        loading={loading} 
        title="个人信息"
        extra={
          <Space>
            <Button 
              type="primary" 
              icon={<EditOutlined />} 
              onClick={showEditModal}
            >
              编辑信息
            </Button>
            <Button 
              type="default" 
              icon={<LockOutlined />} 
              onClick={() => setPasswordModalVisible(true)}
            >
              修改密码
            </Button>
          </Space>
        }
      >
        <Row gutter={[16, 16]}>
          <Col xs={24} sm={24} md={8} lg={6}>
           <div className="avatar-section">
            <Upload
              name="avatar"
              showUploadList={false}
             
              accept="image/*"
              customRequest={({ file }) => handleAvatarUpload({ file })}
            >
              <div className="avatar-upload-wrapper">
                <Avatar 
                  size={128} 
                  src={userInfo.avatar} 
                  icon={<UserOutlined />}
                  className="profile-avatar"
                />
                <div className="avatar-upload-mask">
                  {avatarLoading ? (
                    <LoadingOutlined style={{ fontSize: 24, color: '#fff' }} />
                  ) : (
                    <CameraOutlined style={{ fontSize: 24, color: '#fff' }} />
                  )}
                </div>
              </div>
            </Upload>
            <div className="user-level">
              <Tag color="gold" icon={<StarOutlined />}>
                Lv.{userInfo.level || 0}
              </Tag>
            </div>
          </div>
          </Col>
          <Col xs={24} sm={24} md={16} lg={18}>
            <Descriptions column={1}>
              <Descriptions.Item label="用户名">
                <Tag icon={<UserOutlined />}>{userInfo.username || '未设置'}</Tag>
              </Descriptions.Item>
              <Descriptions.Item label="用户ID">
                <Tag color="blue">{userInfo.userId || '未知'}</Tag>
              </Descriptions.Item>
              <Descriptions.Item label="身份识别号">
                <Tag icon={<IdcardOutlined />}>{userInfo.identificationNumber || '未知'}</Tag>
              </Descriptions.Item>
              <Descriptions.Item label="电子邮箱">
                <Tag icon={<MailOutlined />}>{userInfo.email || '未设置'}</Tag>
              </Descriptions.Item>
              <Descriptions.Item label="注册日期">
                <Tag icon={<CalendarOutlined />}>{userInfo.registrationDate || '未知'}</Tag>
              </Descriptions.Item>
              <Descriptions.Item label="所在地">
                <Tag icon={<EnvironmentOutlined />}>{userInfo.address || '未设置'}</Tag>
              </Descriptions.Item>
              <Descriptions.Item label="用户角色">
                <Tag color="purple">{userInfo.role || '未知'}</Tag>
              </Descriptions.Item>
               <Descriptions.Item label="积分">
                <Tag color="blue">{userInfo.seedPoints || '0'}</Tag>
              </Descriptions.Item>
              {/* 新增字段 */}
  <Descriptions.Item label="每日奖励状态">
    <Tag color={userInfo.dailyAward ? 'green' : 'orange'}>
      {userInfo.dailyAward ? '可领取' : '已领取'}
    </Tag>
  </Descriptions.Item>
  <Descriptions.Item label="不活跃天数">
    <Tag color={userInfo.unactivateDay >= 7 ? 'red' : userInfo.unactivateDay > 3 ? 'orange' : 'green'}>
      {userInfo.unactivateDay} 天
      {userInfo.unactivateDay >= 7 && ' (账号将被封禁)'}
      {userInfo.unactivateDay >= 5 && userInfo.unactivateDay < 7 && ' (接近封禁)'}
    </Tag>
  </Descriptions.Item>
  <Descriptions.Item label="考核剩余天数">
    <Tag color={userInfo.assessDay < 10 ? 'orange' : 'blue'}>
      {userInfo.assessDay} 天
    </Tag>
  </Descriptions.Item>
  <Descriptions.Item label="考核上传量">
    <Progress 
      percent={(userInfo.uploadAssess / (30 * 1024 * 1024 * 1024)) * 100} 
      status={userInfo.uploadAssess >= (30 * 1024 * 1024 * 1024) ? 'success' : 'normal'}
      format={() => `${formatBytes(userInfo.uploadAssess || 0)} / 30GB`}
    />
  </Descriptions.Item>
            </Descriptions>
          </Col>
        </Row>
      </Card>

      <Divider orientation="left">流量统计</Divider>
      
      <Row gutter={[16, 16]}>
        <Col xs={24} sm={12} md={8}>
          <Card>
            <div className="stat-card">
              <div className="stat-icon" style={{ backgroundColor: '#1890ff' }}>
                <CloudUploadOutlined />
              </div>
              <div className="stat-content">
                <h3>上传总量</h3>
                <p>{formatBytes(userInfo.uploadedDelta || 0)}</p>
              </div>
            </div>
          </Card>
        </Col>
        <Col xs={24} sm={12} md={8}>
          <Card>
            <div className="stat-card">
              <div className="stat-icon" style={{ backgroundColor: '#52c41a' }}>
                <CloudDownloadOutlined />
              </div>
              <div className="stat-content">
                <h3>下载总量</h3>
                <p>{formatBytes(userInfo.downloadedDelta || 0)}</p>
              </div>
            </div>
          </Card>
        </Col>
        <Col xs={24} sm={24} md={8}>
          <Card>
            <div className="stat-card">
              <div className="stat-icon" style={{ backgroundColor: getRatioColor(userInfo.sharing_rate || 0) }}>
                <SafetyCertificateOutlined />
              </div>
              <div className="stat-content">
                <h3>分享率</h3>
                <p style={{ color: getRatioColor(userInfo.sharingRate || 0) }}>
                  {(userInfo.sharingRate || 0).toFixed(4)}
                </p>
                <Progress 
                  percent={Math.min((userInfo.sharing_rate || 0) * 100, 100)} 
                  showInfo={false}
                  strokeColor={getRatioColor(userInfo.sharing_rate || 0)}
                />
              </div>
            </div>
          </Card>
        </Col>
      </Row>
      <Divider orientation="left">考核进度</Divider>

<Row gutter={[16, 16]}>
  <Col xs={24} sm={24} md={12}>
    <Card title="上传量考核">
      <Progress 
        percent={(userInfo.uploadAssess / (30 * 1024 * 1024 * 1024)) * 100}
        status={userInfo.uploadAssess >= (30 * 1024 * 1024 * 1024) ? 'success' : 'active'}
        format={() => (
          <div>
            <div>已完成: {formatBytes(userInfo.uploadAssess || 0)}</div>
            <div>目标: 30GB</div>
            <div>剩余天数: {userInfo.assessDay}天</div>
          </div>
        )}
      />
    </Card>
  </Col>
  <Col xs={24} sm={24} md={12}>
    <Card title="活跃度状态">
      <div style={{ marginBottom: 16 }}>
        <strong>不活跃天数: </strong>
        <Tag color={userInfo.unactivateDay >= 7 ? 'red' : userInfo.unactivateDay > 3 ? 'orange' : 'green'}>
          {userInfo.unactivateDay} 天
        </Tag>
        {userInfo.unactivateDay >= 7 && <div style={{ color: 'red', marginTop: 8 }}>警告: 您的账号因长期不活跃将被封禁</div>}
        {userInfo.unactivateDay >= 5 && userInfo.unactivateDay < 7 && <div style={{ color: 'orange', marginTop: 8 }}>警告: 您的账号接近封禁状态</div>}
      </div>
      <div>
        <strong>分享率状态: </strong>
        <Tag color={getRatioColor(userInfo.sharingRate || 0)}>
          {(userInfo.sharingRate || 0).toFixed(4)}
        </Tag>
        {userInfo.sharingRate < 0.4 && <div style={{ color: 'orange', marginTop: 8 }}>当前分享率低于阈值(0.4)，请增加上传量</div>}
      </div>
    </Card>
  </Col>
</Row>

      <Divider orientation="left">客户端配置</Divider>
      
      <Card>
        <Descriptions column={1} bordered>
          <Descriptions.Item label="Passkey">
            <div className="passkey-section">
              <Tag icon={<LinkOutlined />} color="warning">
                {userInfo.passKey || '未获取'}
              </Tag>
              <Button 
                type="link" 
                size="small"
                onClick={() => {
                  navigator.clipboard.writeText(userInfo.passKey);
                  message.success('Passkey已复制到剪贴板');
                }}
              >
                复制
              </Button>
            </div>
            <p className="passkey-hint">
              此密钥用于与BT客户端交互，每个用户唯一。请妥善保管，不要泄露。
            </p>
          </Descriptions.Item>
        </Descriptions>
      </Card>
      <Divider orientation="left">用户操作</Divider>
      
      <Card>
        <Row gutter={16}>
          <Col span={12}>
            <Button 
              type="primary" 
              block 
              onClick={() => setExchangeModalVisible(true)}
            >
              兑换上传量
            </Button>
          </Col>
          
           <Col span={12}>
            <Button 
              type="dashed" 
              block 
              onClick={loadInviteCodes}
              loading={inviteCodesLoading}
            >
              我的邀请码
            </Button>
          </Col>
        </Row>
      </Card>
    {showInviteCodes && (
  <Card 
    title="我的邀请码" 
    style={{ marginTop: 16 }}
    extra={
      <Space>
        <Button 
          type="primary" 
          onClick={() => setInviteModalVisible(true)}
          icon={<PlusOutlined />}
        >
          生成新邀请码
        </Button>
        <Button 
          type="link" 
          onClick={() => setShowInviteCodes(false)}
        >
          收起
        </Button>
      </Space>
    }
  >
    <Table
      columns={inviteColumns}
      dataSource={inviteCodes}
      rowKey="code"
      pagination={false}
      loading={inviteCodesLoading}
      locale={{ emptyText: '暂无邀请码' }}
    />
    <div style={{ marginTop: 16, color: '#888' }}>
      <InfoCircleOutlined /> 提示：点击剩余使用次数或"增加次数"按钮可为邀请码增加使用次数
    </div>
  </Card>
)}
      {/* 兑换上传量模态框 */}
      <Modal
        title="兑换上传量"
        visible={exchangeModalVisible}
        onOk={handleExchangePoints}
        onCancel={() => {
          setExchangeModalVisible(false);
          exchangeForm.resetFields();
        }}
        confirmLoading={loadingExchange}
        okText="确认兑换"
        cancelText="取消"
      >
        <Form form={exchangeForm} layout="vertical">
          <Form.Item
            name="points"
            label="输入要兑换的积分数"
            rules={[
              { required: true, message: '请输入积分数' },
              { type: 'number', min: 1, message: '积分数必须大于0' }
            ]}
          >
            <InputNumber 
              style={{ width: '100%' }} 
              min={1} 
              placeholder="请输入积分数" 
            />
          </Form.Item>
        </Form>
      </Modal>

      {/* 生成邀请码模态框 */}
      <Modal
        title="生成邀请码"
        visible={inviteModalVisible}
        onOk={handleCreateInvite}
        onCancel={() => {
          setInviteModalVisible(false);
          inviteForm.resetFields();
        }}
        confirmLoading={loadingInvite}
        okText="生成"
        cancelText="取消"
      >
        <Form form={inviteForm} layout="vertical">
          <Form.Item
            name="code"
            label="输入至少8位字符的邀请码"
            rules={[
              { required: true, message: '请输入邀请码' },
              { min: 8, message: '邀请码至少需要8个字符' }
            ]}
          >
            <Input placeholder="请输入邀请码" />
          </Form.Item>
        </Form>
      </Modal>

      {/* 编辑信息模态框 */}
      <Modal
        title="编辑个人信息"
        visible={editModalVisible}
        onOk={handleEditSubmit}
        onCancel={() => setEditModalVisible(false)}
        okText="保存"
        cancelText="取消"
      >
        <Form
          form={editForm}
          layout="vertical"
        >
          <Form.Item
            name="username"
            label="用户名"
            rules={[
              { required: true, message: '请输入用户名' },
              { min: 2, max: 16, message: '用户名长度应在2-16个字符之间' }
            ]}
          >
            <Input placeholder="请输入用户名" />
          </Form.Item>
          <Form.Item
            name="address"
            label="所在地"
            rules={[
              { required: true, message: '请输入所在地' },
              { max: 30, message: '所在地长度不能超过30个字符' }
            ]}
          >
            <Input placeholder="请输入所在地" />
          </Form.Item>
        </Form>
      </Modal>

      {/* 修改密码模态框 */}
      <Modal
        title="修改密码"
        visible={passwordModalVisible}
        onOk={handlePasswordSubmit}
        onCancel={() => {
          setPasswordModalVisible(false);
          passwordForm.resetFields();
        }}
        okText="确认修改"
        cancelText="取消"
      >
        <Form
          form={passwordForm}
          layout="vertical"
        >
          <Form.Item
            name="newPassword"
            label="新密码"
            rules={[
              { required: true, message: '请输入新密码' },
              { min: 6, max: 20, message: '密码长度应在6-20个字符之间' }
            ]}
          >
            <Input.Password placeholder="请输入新密码" />
          </Form.Item>
          <Form.Item
            name="confirmPassword"
            label="确认新密码"
            dependencies={['newPassword']}
            rules={[
              { required: true, message: '请再次输入新密码' },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || getFieldValue('newPassword') === value) {
                    return Promise.resolve();
                  }
                  return Promise.reject(new Error('两次输入的密码不一致'));
                },
              }),
            ]}
          >
            <Input.Password placeholder="请再次输入新密码" />
          </Form.Item>
          <Form.Item
            name="verificationCode"
            label="验证码"
            rules={[
              { required: true, message: '请输入验证码' },
              { pattern: /^\d{6}$/, message: '验证码必须是6位数字' }
            ]}
          >
            <div style={{ display: 'flex', alignItems: 'center' }}>
              <Input 
                placeholder="请输入6位验证码" 
                style={{ flex: 1, marginRight: 8 }}
              />
              <Button 
                onClick={sendVerificationCode} 
                disabled={countdown > 0 || sendingCode}
              >
                {sendingCode ? <Spin size="small" /> : countdown > 0 ? `${countdown}秒后重试` : '获取验证码'}
              </Button>
            </div>
          </Form.Item>
        </Form>
      </Modal>
    </div>
    </RouterAuth>
  );
};

export default Profile;